package cn.ynrcb.personnelfile.admin.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.ynrcb.personnelfile.admin.dao.FileDao;
import cn.ynrcb.personnelfile.admin.param.DemandInfoAuditParam;
import cn.ynrcb.personnelfile.admin.entity.FileEntity;
import cn.ynrcb.personnelfile.admin.param.DemandInfoListParam;
import cn.ynrcb.personnelfile.common.annotation.BusinessLog;
import cn.ynrcb.personnelfile.common.utils.DateUtils;
import cn.ynrcb.personnelfile.common.validator.ValidatorUtils;
import cn.ynrcb.personnelfile.common.validator.group.AddGroup;
import cn.ynrcb.personnelfile.common.validator.group.UpdateGroup;
import cn.ynrcb.personnelfile.sysadmin.controller.AbstractController;
import cn.ynrcb.personnelfile.common.utils.PageUtils;
import cn.ynrcb.personnelfile.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import cn.ynrcb.personnelfile.admin.entity.DemandInfoEntity;
import cn.ynrcb.personnelfile.admin.service.DemandInfoService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;


/**
 * 整改需求信息表
 *
 * @author wujianfan
 * @email fanxipo@qq.com
 * @date 2022-12-06 23:14:59
 */
@Api(value = "整改需求系统",tags = {"业务相关=>整改需求信息相关接口"})
@RestController
@RequestMapping("admin/demandinfo")
public class DemandInfoController extends AbstractController {
    @Autowired
    private DemandInfoService demandInfoService;
    @Value("${uploadFilePath}")
    private String uploadFilePath;
    @Autowired
    private FileDao fileDao;

    /**
     * 文件上传
     *
     * @param file
     * @param req
     * @return
     */
    @ApiOperation("文件上传")
    @ApiImplicitParam(name = "file", value = "附件",example ="123.jpg", required = true)
    @BusinessLog("文件上传")
    @PostMapping("/upload")
    public Map<String, Object> fileUpload(MultipartFile file, HttpServletRequest req) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");
        Map<String, Object> resultMap = new HashMap<>();
        // 得到上传时的文件名
        String originName = file.getOriginalFilename();
        String strFormat = simpleDateFormat.format(new Date());
        String realPath = uploadFilePath + strFormat;
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        // 保存文件对象，加上uuid是为了防止文件重名
        String strNewFileName = UUID.randomUUID().toString().replaceAll("-", "") + originName.substring(originName.lastIndexOf("."));
        try {
            file.transferTo(new File(folder, strNewFileName));
            String strUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/" + strFormat + strNewFileName;
            resultMap.put("status", "success");
            resultMap.put("url", strUrl);
            resultMap.put("filePath", "/" + strFormat + strNewFileName);
            if (originName.length() > 20) {
                resultMap.put("fileName", org.apache.commons.lang3.StringUtils.substring(originName, 0, 20) + "···");
            } else {
                resultMap.put("fileName", originName);
            }
            FileEntity vo = new FileEntity();
            vo.setId(RandomUtil.randomUUID().replaceAll("-", ""));
            vo.setFileName(originName);
            vo.setFilePath("/" + strFormat + strNewFileName);
            fileDao.saveFile(vo.getId(), vo.getFileName(), vo.getFilePath());
            resultMap.put("fileId", vo.getId());
        } catch (IOException e) {
            e.printStackTrace();
            resultMap.put("status", "error");
            resultMap.put("msg", e.getMessage());
        }
        return resultMap;
    }

    /**
     * 移除文件时删除数据库数据（直接删除文件）
     *
     * @param id
     * @return
     */
    @ApiOperation("移除文件时删除数据库数据（直接删除文件）")
    @ApiImplicitParam(name = "id", value = "附件id",example ="1", required = true)
    @BusinessLog("附件真删")
    @PostMapping("/deleteFile")
    public R deleteFile(String id) {
        FileEntity entity = fileDao.getFileById(id);
        String s = uploadFilePath.substring(0, uploadFilePath.length() - 1) + entity.getFilePath();
        FileUtil.del(new File(s));
        fileDao.deleteByFileId(id);
        return R.ok();
    }

    /**
     * 需求信息管理列表
     */
    @ApiOperation("需求信息管理列表")
    @ApiImplicitParam(name = "id", value = "需求信息id",example ="1", required = true)
    @GetMapping("/list")
    @RequiresPermissions("admin:demandinfo:list")
    public R list(@RequestBody DemandInfoListParam params){
        PageUtils page = demandInfoService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 我的需求信息列表
     */
    @ApiOperation("我的需求信息列表")
    @ApiImplicitParam(name = "id", value = "需求信息id",example ="1", required = true)
    @GetMapping("/mylist")
    @RequiresPermissions("admin:demandinfo:mylist")
    public R myList(@RequestBody DemandInfoListParam params){
        PageUtils page = demandInfoService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 需求信息
     */
    @ApiOperation("需求信息")
    @ApiImplicitParam(name = "id", value = "需求信息id",example ="1", required = true)
    @GetMapping("/info/{id}")
    @RequiresPermissions("admin:demandinfo:info")
    public R info(@PathVariable("id") Long id){
		DemandInfoEntity demandInfo = demandInfoService.getById(id);
        //处理附件
        ArrayList<Object> photoList = new ArrayList<>();
        String[] split = demandInfo.getSitePhoto().split(",");
        for (String s : split) {
            FileEntity file = fileDao.getFileById(s);
            HashMap<Object, Object> photoMap = new HashMap<>();
            if (!StringUtils.isEmpty(file)) {
                if (file.getFileName().length() > 20) {
                    photoMap.put("name", org.apache.commons.lang3.StringUtils.substring(file.getFileName(), 0, 20) + "···");
                } else {
                    photoMap.put("name", file.getFileName());
                }
                photoMap.put("url", file.getFilePath());
                photoMap.put("id", file.getId());
                photoList.add(photoMap);
            }
        }

        return R.ok().put("demandInfo", demandInfo).put("photoList",photoList);
    }

    /**
     * 需求信息新增/保存
     */
    @BusinessLog("需求信息新增/保存")
    @ApiOperation("需求信息新增/保存")
    @PostMapping("/save")
    @RequiresPermissions("admin:demandinfo:save")
    public R save(@RequestBody DemandInfoEntity demandInfo){
        ValidatorUtils.validateEntity(demandInfo, AddGroup.class);
        //编辑工单号
        String orderNumber = "ZGXQ";
        //获取时间字符串，随机生成工单号
        orderNumber += DateUtils.getYear() + DateUtils.getMonth() + DateUtils.getDay() + (int)(Math.random()*(10-1)+1) + (int)(Math.random()*(10-1)+1) + (int)(Math.random()*(10-1)+1);
        demandInfo.setOrderNumber(orderNumber);
        demandInfo.setCreatTime(new Date());
        demandInfo.setCreatUserId(getCurrentUserId());
		demandInfoService.save(demandInfo);

        return R.ok();
    }

    /**
     * 需求信息修改
     */
    @ApiOperation("需求信息修改")
    @BusinessLog("需求信息修改")
    @PostMapping("/update")
    @RequiresPermissions("admin:demandinfo:update")
    public R update(@RequestBody DemandInfoEntity demandInfo){
        ValidatorUtils.validateEntity(demandInfo, UpdateGroup.class);
        demandInfo.setUpdateTime(new Date());
        demandInfo.setUpdateUserId(getCurrentUserId());
		demandInfoService.updateById(demandInfo);

        return R.ok();
    }

    /**
     * 需求信息整改处理
     */
    @ApiOperation("需求信息整改处理")
    @BusinessLog("需求信息整改处理")
    @GetMapping("/deal")
    @RequiresPermissions("admin:demandinfo:deal")
    public R deal(Long id,String inopOrderNumber){
        if(ObjectUtil.isNotNull(id)){
            DemandInfoEntity demandInfo = demandInfoService.getById(id);
            if(ObjectUtil.isNotNull(demandInfo)){
                demandInfo.setInopOrderNumber(inopOrderNumber);
                demandInfo.setUpdateTime(new Date());
                demandInfo.setUpdateUserId(getCurrentUserId());
                demandInfoService.updateById(demandInfo);
            }else {
                return R.error("找不到需求信息");
            }
            return R.ok();
        }else {
            return R.error("需求信息id不能为空");
        }

    }

    /**
     * 需求信息审核
     */
    @ApiOperation("需求信息审核")
    @BusinessLog("需求信息审核")
    @PostMapping("/audit")
    @RequiresPermissions("admin:demandinfo:audit")
    public R audit(@RequestBody DemandInfoAuditParam demandInfoAuditParam){
        ValidatorUtils.validateEntity(demandInfoAuditParam, UpdateGroup.class);
        DemandInfoEntity demandInfo = demandInfoService.getById(demandInfoAuditParam.getId());
        if(ObjectUtil.isNotNull(demandInfo)){
            //判断是否审核通过
            if(demandInfoAuditParam.getIsAudit()){
                demandInfo.setAuditStatus(1);
                demandInfo.setDealUserIds(demandInfoAuditParam.getDealUserIds());
            }else {
                demandInfo.setAuditStatus(2);
            }
            demandInfo.setAuditRemark(demandInfoAuditParam.getAuditRemark());
            demandInfo.setAuditUserId(getCurrentUserId());
            demandInfo.setAuditTime(new Date());
            demandInfoService.updateById(demandInfo);
        }else {
            return R.error("找不到数据对象");
        }
        return R.ok();
    }

    /**
     * 整改处理审核
     */
    @ApiOperation("整改处理审核")
    @BusinessLog("整改处理审核")
    @PostMapping("/dealaudit")
    @RequiresPermissions("admin:demandinfo:dealaudit")
    public R dealAudit(@RequestBody DemandInfoAuditParam demandInfoAuditParam){
        ValidatorUtils.validateEntity(demandInfoAuditParam, UpdateGroup.class);
        DemandInfoEntity demandInfo = demandInfoService.getById(demandInfoAuditParam.getId());
        if(ObjectUtil.isNotNull(demandInfo)){
            //判断是否审核通过
            if(demandInfoAuditParam.getIsAudit()){
                demandInfo.setDealAuditStatus(1);
            }else {
                demandInfo.setDealAuditStatus(2);
            }
            demandInfo.setDealAuditRemark(demandInfoAuditParam.getAuditRemark());
            demandInfo.setDealAuditUserId(getCurrentUserId());
            demandInfo.setDealAuditTime(new Date());
            demandInfoService.updateById(demandInfo);
        }else {
            return R.error("找不到数据对象");
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @GetMapping("/delete")
    @RequiresPermissions("admin:demandinfo:delete")
    public R delete(@RequestBody Long[] ids){
		demandInfoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
